/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package io.simple.filters;

import io.simple.core.RequestContext;
import io.simple.core.chain.Filter;
import io.simple.signals.Signal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import simple.utils.concurrent.ConcurrentProperties;

import java.nio.ByteBuffer;

/**
 * @author Tom
 */
public class OptionsFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(OptionsFilter.class);
    private static final String MAX_AGE = "1728000";
    public static final String METHOD = "method";
    public static final String OPTIONS = "OPTIONS";

    @Override
    public ByteBuffer filter(RequestContext ctx, ByteBuffer data) throws Signal {
        String method = (String) ctx.getProperty(METHOD);
        ConcurrentProperties<String> props = createProps(ctx);
        if (method != null && method.equalsIgnoreCase(OPTIONS)) {
            LOGGER.debug("OPTIONS request!");
            // return
            throw new Signal(200, "", props.getBackingMap());
        } else {
            // Origin
            LOGGER.debug("Not an OPTIONS request, but setting allow all headers");
            for (String n : props.getPropNames()) {
                ctx.getResponseHeaders().set(n, props.get(n));
            }
        }
        return data;
    }

    private ConcurrentProperties<String> createProps(RequestContext ctx) {
        // allow everything
        // ----------------
        ConcurrentProperties<String> props = new ConcurrentProperties<>();
        // Access-Control-Request-Method
        String requestMethods = ctx.getRequestHeaders().get("Access-Control-Request-Method");
        props.set("Access-Control-Allow-Methods", requestMethods);
        // Access-Control-Request-Headers
        String requestHeaders = ctx.getRequestHeaders().get("Access-Control-Request-Headers");
        props.set("Access-Control-Allow-Headers", requestHeaders);
        // Credentials
        props.set("Access-Control-Allow-Credentials", "true");
        // Origin
        String origin = ctx.getRequestHeaders().get("Origin");
        props.set("Access-Control-Allow-Origin", origin);
        // Max-Age
        props.set("Access-Control-Max-Age", MAX_AGE);
        return props;
    }

    @Override
    public void close() throws Exception {
        //To change body of implemented methods use File | Settings | File Templates.
    }


}
